﻿
using System.IO;
using System;
using Pretext.Logging;

namespace Pretext {
    public static class Pretexter {

        public static bool VerboseMode { get; set; }

		public static string WorkingDirectory { get; set; }

        public static PretextSession Session = new PretextSession();

		public static string LoadAndProcessFile(string filename, Token relatedToken) {

			return ProcessString(LoadFile(filename, relatedToken), filename);

        }

        public static string LoadFile(string filename, Token relatedToken)
        {

			Session.AddLogItem(new Pretext.Logging.LogItem(LogItemType.HigherLevelInfo, "Loading file " + filename + "...", relatedToken));

            string fullFilename = filename;

            if (!string.IsNullOrEmpty(WorkingDirectory))
                fullFilename = WorkingDirectory + @"\" + filename;

			WorkingDirectory = Path.GetDirectoryName(fullFilename);

			string output = null;

			try {
				output = File.ReadAllText(fullFilename);
			} catch (FileNotFoundException ex) {
				Session.AddLogItem(new Pretext.Logging.LogItem(Pretext.Logging.LogItemType.Error, ex.Message, relatedToken));
			}

			return output;

        }

        public static string ProcessString(string source, string sourceFileDescription) {

            TokenParser p = new TokenParser(Session);
            p.Tokens.AddRange(Tokenizer.GetTokens(source, sourceFileDescription));
            
            p.Process();

            return p.Output.ToString();

        }

        /// <summary>
        /// Tests to see whether the TokenType is an operator type or not.
        /// </summary>
        /// <param name="type">The type to test.</param>
        /// <returns></returns>
        public static bool IsOperator(TokenType type) {
            return
                type == TokenType.EqualityOperator ||
                type == TokenType.InequalityOperator;
        }
 
    }
}